/**
 * @Description: 统计所有接口
 * @Author 卞鹏飞 <228443632@qq.com>
 * @create 04/12/24 PM6:35
 */

import { groupBy, isFunction, isObject, isString, requireAllModule } from 'sf-utils2'
;(async function () {
  if (process.env.NODE_ENV !== 'production') {
    const modules = requireAllModule({
      requireContext: require.context('./modules', true, /\.(js|ts)$/)
    })

    const apis = []

    modules.forEach(([value]) => {
      if (isObject(value?.default)) {
        apis.push(...Object.values(value?.default))
      }
    })

    const urlInfoList = []

    const xhrOpen = XMLHttpRequest.prototype.open
    XMLHttpRequest.prototype.open = function () {
      console.log('arguments', arguments)
      urlInfoList.push({
        method: arguments[0],
        url: arguments[1]
      })
      return xhrOpen.apply(this, arguments)
    }
    Object.defineProperty(XMLHttpRequest.prototype, 'timeout', {
      get() {
        return 20
      }
      // set() {
      //   timeout = 20
      // }
    })

    console.log('apis', apis)
    await Promise.allSettled(
      apis
        .map((api) => {
          if (isFunction(api)) {
            return api([])
          }
          urlInfoList.push({
            method: undefined,
            url: api
          })
          return undefined
        })
        .filter(Boolean)
    )

    console.log('modules', {
      apis,
      urlInfoList
    })

    const urls = groupBy(urlInfoList, (item) => {
      console.log('item.url', item.url)
      if (isString(item.url)) {
        const key = (item.url || '').split('/').filter(Boolean).slice(0, 2).join('/')
        return key
      }
      return false
    })

    console.log('modules输出的结果api路径是', {
      urls
    })
  }
})()
